﻿using Iot.Models;

namespace Iot.Services
{

    public interface IPlansService
    {
        Task ExecuteAsync(CancellationToken stoppingToken);
    }

    public class PlansService : IPlansService
    {
        private static IClientWorker? _clientWorker;

        public PlansService(IServiceProvider provider)
        {
            _clientWorker = provider.GetRequiredService<IClientWorker>();
        }

        public async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //所有的开关
            var sds = AppData.AppConfig.Switchs;
            while (!stoppingToken.IsCancellationRequested)
            {
                foreach (var sd in sds)
                {
                    //"070000,1|070500,0|080000,1|080500,0"
                    if (string.IsNullOrEmpty(sd.Plans))
                        continue;

                    List<Plan> ps = GetPlansFromString(sd.Plans);
                    var currentTime = DateTime.Now.ToString("HHmmss");
                    var find = ps.Where(p => p.ExecuteTime == currentTime);
                    if (find.Any())
                    {
                        var item = find.First();
                        await _clientWorker?.PublishAsync(MQTTTOPIC.CONTROL, new MQTTMessage() { Msg = $"{item.Status}", To = sd.DeviceMAC, GPIO = sd.GPIO })!;
                        await _clientWorker?.PublishAsync(MQTTTOPIC.CONTROL, new MQTTMessage() { Msg = $"2", To = sd.DeviceMAC, GPIO = sd.GPIO })!;
                    }
                }

                //周期性任务，于上次任务执行完成后，等待1秒，执行下一次任务
                await Task.Delay(1000, stoppingToken);
            }
        }

        private class Plan
        {
            public string? ExecuteTime { get; set; }
            public string? Status { get; set; }
        }

        private List<Plan> GetPlansFromString(string plans)
        {
            List<Plan> r = [];
            var ps = plans.Split("|");
            foreach (var p in ps)
            {
                var s = p.Split(",");
                r.Add(new Plan()
                {
                    ExecuteTime = s.First(),
                    Status = s.Last()
                });
            }

            return r;
        }
    }
}
